<template>
    <div class="invoice_form_container">
        <el-form ref="invoiceForm" :rules="rules" :model="formData" label-width="8em"
                 v-enterToNext>
            <el-row :gutter="15">
                <el-col :span="8">
                    <el-form-item label="票据类型" prop="invoice_type">
                        <el-select v-model="formData.invoice_type" placeholder="请选择票据信息"
                                   :disabled="!isEditFlag" style="width: 100%;">
                            <el-option v-for="(item, index) in filterInvoiceType" :key="index"
                                       :label="item.label" :value="item.value" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8" v-if="invoiceList.length > 1 && $utils.isEmpty(formData.id)">
                    <el-form-item label="发票" prop="entity_sid">
                        <el-select v-model="formData.entity_sid" placeholder="请选择发票"
                                   style="width: 100%;" @change="handleChangeInvoice">
                            <el-option v-for="(item, index) in invoiceList" :key="index"
                                       :label="item.entity_name" :value="item.sid" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="发票抬头" prop="entity_name">
                        <el-input v-model="formData.entity_name" placeholder="请输入发票抬头"
                                  autocomplete="off" clearable :disabled="!isEditFlag" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="纳税人识别号" prop="entity_code">
                        <el-input v-model="formData.entity_code" placeholder="请输入纳税人识别号"
                                  autocomplete="off" clearable :disabled="!isEditFlag" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="电话" prop="entity_phone">
                        <el-input v-model="formData.entity_phone" placeholder="请输入电话"
                                  autocomplete="off" clearable :disabled="!isEditFlag" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="开户行" prop="entity_bank">
                        <el-input v-model="formData.entity_bank" placeholder="请输入开户行"
                                  autocomplete="off" clearable :disabled="!isEditFlag" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="开户账号" prop="entity_bank_account">
                        <el-input v-model="formData.entity_bank_account" placeholder="请输入开户账号"
                                  autocomplete="off" clearable :disabled="!isEditFlag" />
                    </el-form-item>
                </el-col>
                <el-col :span="invoiceList.length > 1 ? (isGen ? 8 : 16) : (isGen ? 16 : 24)">
                    <el-form-item label="地址" prop="entity_address">
                        <el-input v-model="formData.entity_address" placeholder="请输入地址"
                                  autocomplete="off" clearable :disabled="!isEditFlag" />
                    </el-form-item>
                </el-col>
                <el-col :span="8" v-if="isGen">
                    <el-form-item :label="`保留未${ type === 'buy' ? '收' : '开' }票`">
                        <el-checkbox v-model="formData.keep_un_invoice" @change="handleChangeKeepUnInvoice" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label-width="0">
                        <vxe-table-template :data="dataList" :options.sync="tableOptions" />
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="备注" prop="note_info">
                        <el-input v-model="formData.note_info" autocomplete="off" clearable
                                  type="textarea" row="4" :disabled="!isEditFlag" />
                    </el-form-item>
                </el-col>
            </el-row>
        </el-form>
    </div>
</template>

<script>
import { mapState } from "vuex";
import clothing from "@jxc/utils/clothing";

export default {
    name: "InvoiceForm",
    props: {
        type: {
            type: String,
            default: 'buy',
        },
        row: {
            type: Object,
            default: null,
        },
        invoiceTypeList: {
            type: Array,
            default: () => [],
        },
        detail: {
            type: Boolean,
            default: false,
        },
        audit: {
            type: Boolean,
            default: false,
        },
    },
    data() {
        const _this = this;
        return {
            rules: {
                entity_name: [
                    { required: true, message: "请输入发票抬头", trigger: "blur" },
                ],
                entity_code: [
                    { required: true, message: "请输入纳税人识别号", trigger: "blur" },
                ],
            },
            invoiceList: [],
            formData: {},
            dataList: [],
            tableOptions: {
                ref: "JxcInvoiceFormTable",
                showSummary: true,
                summaryArray: [ 'qty', 'amount' ],
                columns: [],
                baseColumns: [
                    {
                        label: "销售单号",
                        prop: "order_code",
                        align: "center",
                        permission: ['sale'],
                    },
                    {
                        label: "采购单号",
                        prop: "order_code",
                        align: "center",
                        permission: ['buy'],
                    },
                    {
                        label: "物料",
                        prop: "goods_name",
                        align: "center",
                        permission: ['sale', 'buy'],
                    },
                    {
                        label: "规格",
                        prop: "goods_spec",
                        align: "center",
                        permission: ['sale', 'buy'],
                    },
                    {
                        label: "计量单位",
                        prop: "goods_unit",
                        align: "center",
                        width: 90,
                        permission: ['sale', 'buy'],
                    },
                    {
                        label: "数量",
                        prop: "qty",
                        align: "center",
                        minWidth: 100,
                        permission: ['sale', 'buy'],
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 3, true),
                    },
                    {
                        label: "单价",
                        prop: "price",
                        align: "center",
                        minWidth: 100,
                        permission: ['sale', 'buy'],
                        editRender: {
                            name: "CustomInput",
                            autoselect: true,
                            props: {
                                doubleInput: {
                                    len: 4,
                                    negative: false,
                                },
                            },
                            events: {
                                input: _this.rewriteChangeRow,
                            },
                        },
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 4, true),
                    },
                    {
                        label: "金额",
                        prop: "amount",
                        align: "center",
                        minWidth: 100,
                        permission: ['sale', 'buy'],
                        formatter: (row, column, scope) => _this.formatterAmount(row, column, scope, 4, true),
                    },
                ],
                operates: {
                    fixed: "right",
                    list: [
                        {
                            id: 'del',
                            icon: 'fa fa-trash-o',
                            size: 'mini',
                            type: 'danger',
                            show: true,
                            tooltip: {
                                content: '删除',
                            },
                            filter() {
                                return _this.$utils.isEmpty(_this.formData.sid);
                            },
                            method: (index, row) => {
                                let dataList = _this.dataList.map(item => $.extend({}, item));
                                dataList = dataList.filter(item => item._index !== row._index);
                                _this.dataList = _this.resetIndex(dataList);
                            }
                        }
                    ],
                },
                pagination: false,
            },
        };
    },
    computed: {
        ...mapState('jxc', ['setting']),
        filterInvoiceType() {
            let list = (this.invoiceTypeList || []).map(item => $.extend({}, item));
            list = list.filter(item => item.value !== 0);
            return list;
        },
        isEditFlag() {
            if (this.detail) {
                return false;
            }
            return this.$utils.isEmpty(this.formData.audit_state) || this.formData.audit_state === 0;
        },
        isGen() {
            return this.$utils.isEmpty(this.formData.sid);
        },
    },
    watch: {
        row: {
            handler() {
                this.init();
            },
            deep: true,
            immediate: true,
        },
    },
    methods: {
        async init() {
            const _this = this;
            if (!_this.row) {
                return;
            }
            await _this.storeDispatch('jxc/initSetting');
            if (_this.detail) {
                _this.rules = {};
            }
            if (_this.type === 'buy' && _this.$utils.isEmpty(_this.row.sid)) {
                await _this.initInvoiceList();
            }
            if (_this.$refs.invoiceForm) {
                _this.$refs.invoiceForm.clearValidate();
            }
            if (_this.$utils.isNotEmpty(_this.row.sid) || _this.$utils.isNotEmptyList(_this.row.selected_list)) {
                await _this.initData();
            }
            _this.initTableOptions();
        },
        initTableOptions() {
            const _this = this;
            let columns = _this.tableOptions.baseColumns.map(item => $.extend({}, item));
            columns = columns.filter(item => item.permission.indexOf(_this.type) !== -1);
            columns = clothing.resetTableColumns(_this.setting, columns, 'qty', (row, column) => {
                let { params } = column;
                let keys = Object.keys(row.preset_order_map || {});
                return keys.indexOf(params.label) !== -1;
            });
            let operates = $.extend({}, _this.tableOptions.operates);
            if (_this.$utils.isNotEmpty(_this.formData.sid)) {
                columns = columns.map(item => {
                    let obj = $.extend({}, item);
                    delete obj.editRender;
                    return obj;
                });
                operates = {};
            }
            _this.tableOptions = $.extend({}, _this.tableOptions, {
                columns,
                operates,
                getMaxHeight() {
                    let height = $(_this.getActiveTabsContainer()).height();
                    return height * 0.8 - 250;
                },
            });
        },
        initInvoiceList() {
            const _this = this;
            return _this.fetchData(_this.$api.API_FindBaseInvoiceInfos, {
                owner_sid: '-1',
                nopage: '1',
            }).then(res => {
                _this.invoiceList = res.data || [];
                if (_this.$utils.isNotEmptyList(_this.invoiceList) && _this.invoiceList.length > 1) {
                    _this.handleChangeInvoice(_this.invoiceList[0].sid);
                }
            });
        },
        handleChangeInvoice(value) {
            const _this = this;
            let filter = this.invoiceList.filter(item => item.sid === value);
            if (_this.$utils.isNotEmptyList(filter)) {
                _this.formData = $.extend({}, _this.formData, {
                    entity_sid: value,
                    entity_name: filter[0].entity_name,
                    entity_code: filter[0].entity_code,
                    entity_phone: filter[0].entity_phone,
                    entity_address: filter[0].entity_address,
                    entity_bank: filter[0].entity_bank,
                    entity_bank_account: filter[0].entity_bank_account,
                });
            }
        },
        initData() {
            const _this = this;
            let url = _this.$api.API_GetJxcBuyOrder2InvoiceData;
            let params = {
                sid_list: _this.row.selected_list,
            };
            if (_this.type === 'sale') {
                url = _this.$api.API_GetJxcSaleOrder2InvoiceData;
            }
            if (_this.$utils.isNotEmpty(_this.row.sid)) {
                url = _this.$api.API_GetJxcInvoiceBySid;
                params = {
                    sid: _this.row.sid,
                };
            }
            return _this.fetchData(url, params).then(res => {
                let resData = res.data || {};
                _this.formData = $.extend({}, resData, {
                    invoice_type: _this.$utils.isNotEmpty(params.sid) ? resData.invoice_type : _this.filterInvoiceType[0].value,
                });
                let dataList = clothing.transferDetailList(_this.setting, resData.detail_list, _this.tableOptions.columns);
                _this.dataList = _this.resetIndex(dataList);
                if (_this.$utils.isEmpty(_this.row.sid)) {
                    _this.handleChangeKeepUnInvoice(true);
                }
                if (_this.$utils.isNotEmptyList(_this.invoiceList)) {
                    _this.handleChangeInvoice(_this.invoiceList[0].sid);
                }
            }).catch(() => {
            });
        },
        rewriteChangeRow({ row, column }) {
            const _this = this;
            column = Object.assign({}, column, column.params)
            // 手动限制控制数字位数
            if (column.editRender && column.editRender.double) {
                _this.$set(row, column.prop, _this.$XEUtils.DoubleInput(row[column.prop], column.editRender.double));
            }
            if (column.editRender && column.editRender.integer) {
                _this.$set(row, column.prop, _this.$XEUtils.IntInput(row[column.prop]));
            }
            if (column.prop === 'price') {
                if (_this.$utils.isNotEmpty(row.qty) && _this.$utils.isNotEmpty(row.price)) {
                    let amount = _this.$utils.accMul(row.qty, row.price);
                    _this.$set(row, "amount", amount);
                }
            }
        },
        handleChangeKeepUnInvoice(value) {
            const _this = this;
            _this.formData = $.extend({}, _this.formData, {
                keep_un_invoice: value,
            });
            _this.dataList = _this.dataList.map(item => {
                let obj = $.extend({}, item);
                obj.price = value ? item.un_invoice_price : item.order_detail_price;
                obj.amount = value ? item.un_invoice_amount : item.order_detail_amount;
                return obj;
            });
        },
        async confirm() {
            const _this = this;
            let valid = await _this.validateForm('invoiceForm');
            if (!valid) {
                return false;
            }
            let dataList = _this.dataList.filter(item => $.extend({}, item));
            if (!_this.$utils.isNotEmptyList(dataList)) {
                _this.$message.error(`${ _this.type === 'buy' ? '收' : '开' }票明细不能为空`);
                return false;
            }
            let filter = dataList.filter(item => _this.$utils.isNotEmpty(item.qty) && Number(item.qty) === 0);
            if (_this.$utils.isNotEmptyList(filter)) {
                _this.$message.error(`第${ filter[0]._index + 1 }项${ _this.type === 'buy' ? '收' : '开' }票明细数量不能为空`);
                return false;
            }
            dataList = clothing.procSubData(_this.setting, dataList);
            let subData = $.extend({}, _this.formData);
            subData.detail_list = dataList.map(item => {
                let obj = $.extend({}, item);
                obj.sn = item._index + 1;
                delete obj.amount;
                return obj;
            });
            let url = _this.$api.API_SaveJxcInvoice;
            if (_this.audit) {
                url = _this.$api.API_SaveJxcInvoiceWithAudit;
            }
            return _this.fetchData(url, subData).then(() => {
                if (_this.audit) {
                    _this.$message.success('审核成功！');
                } else {
                    if (_this.$utils.isEmpty(subData.id)) {
                        _this.$message.success('申请成功！');
                    } else {
                        _this.$message.success('保存成功！');
                    }
                }
                return true;
            }).catch(() => {
                return false;
            });
        },
    },
}
</script>

<style lang="less" rel="stylesheet/less" scoped>
.invoice_form_container {
    width: 100%;
    height: 100%;
}
</style>
